/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.apps.epocket.stripes.util;

import java.io.*;


/**
 *
 * @author fikri
 */
public class FileUtil {    
    

    public FileUtil() {
    }    

    public String saveFile(String uploadLocation, String fileName, InputStream inputStream) throws Exception {
//        String genFileName = System.nanoTime() + "_" + fileName;
        File dir = new File(uploadLocation);
        if (!dir.exists()) {
            dir.mkdirs();
            dir.setReadable(true, false);
            dir.setExecutable(true, false);
        }
        File file = new File(uploadLocation + (uploadLocation.endsWith(File.separator) ? "" : File.separator) + fileName);
        FileOutputStream out = new FileOutputStream(file);
        FileUtil.copyStream(inputStream, out);
        out.close();
        file.setReadable(true, false);
        return file.getName();
    }

    public File getFile(String uploadLocation, String fileName) {
        File file = new File(uploadLocation + (uploadLocation.endsWith(File.separator) ? "" : File.separator) + fileName);
        if (file.exists()) {
            return file;
        }
        return null;
    }

    public void deleteFile(String uploadLocation, String fileName) {
        File file = new File(uploadLocation + (uploadLocation.endsWith(File.separator) ? "" : File.separator) + fileName);
        if (file.exists()) {
            file.delete();
        }
    }

    public String writeAsString(File file, String contents) {
        Writer out = null;
        try {
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) {
                return "unable to make parent dir for " + file;
            }
            Reader in = new StringReader(contents);
            out = new FileWriter(file);
            FileUtil.copyStream(in, out);
            return null;
        } catch (IOException e) {
            return "[FileUtil] ERROR writing file : " + e.getMessage();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                } // ignored
            }
        }
    }

    public static void copyStream(InputStream in, OutputStream out) throws IOException {
        final int MAX = 4096;
        byte[] buf = new byte[MAX];
        for (int bytesRead = in.read(buf, 0, MAX);
                bytesRead != -1;
                bytesRead = in.read(buf, 0, MAX)) {
            out.write(buf, 0, bytesRead);
        }
    }

    public static void copyStream(Reader in, Writer out) throws IOException {
        final int MAX = 4096;
        char[] buf = new char[MAX];
        for (int bytesRead = in.read(buf, 0, MAX);
                bytesRead != -1;
                bytesRead = in.read(buf, 0, MAX)) {
            out.write(buf, 0, bytesRead);
        }
    }

    
    
}
